package com.kadron.jobs;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import javax.transaction.UserTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.transaction.Transaction;

import com.kadron.common.KUtil;
import com.kadron.dao.KUserDAO;
import com.kadron.service.KUserService;
import com.kadron.transaction.KTx;

@AutoCreate
@Name(KUserTypeUpdateJob.K_NAME)
@Scope(ScopeType.EVENT)
public class KUserTypeUpdateJob extends TimerTask {
	
	public static final String K_NAME = "KUserTypeUpdateJob";
	protected static final String INFO_MESASGE = "RUN job"+K_NAME;
	
	private static final Log log = LogFactory.getLog(KUserTypeUpdateJob.class);

	@In
	private KUserDAO userDAO;
	
	@In
	private KUserService userService;
	
	@Override
	public void run() {
		if (log.isInfoEnabled()) {
			log.info(INFO_MESASGE);
		}
		Date moment = KUtil.getMoment();
		
		UserTransaction transaction = null;
		try {
			transaction = Transaction.instance();
			List<Long> userIds = userDAO.getUsersForUpdateType(moment);
			for (Long userId : userIds) {				
				userService.checkStatus(userId);
				KTx.commit(transaction);
				KTx.begin(transaction);
			}
		} catch (Exception e) {
			e.printStackTrace();
			KTx.rollback(transaction);
			KTx.begin(transaction);
		}
	}

	
	
}
